package cate.game.framework;

import cate.common.util.GameResult;
import cp.solution.business.game.component.NoticeParam;
import easy.java.practice.errorcode.EcException;
import easy.java.util.StrTool;
import org.apache.commons.lang3.ArrayUtils;

public class GameException extends EcException {

    public int contentId;

    public NoticeParam[] paramList;

    public GameException() {
        this.code = GameResult.FAIL;
    }

    public GameException(GameResult r) {
        this.code = r.code;
        this.message = r.message;
        this.contentId = r.contentId;
        this.paramList = r.paramList;
    }

    public GameException(Throwable e) {
        this.code = GameResult.FAIL;
        this.message = e.getMessage();
        this.content(e.getMessage());
    }

    public GameException code(int code) {
        this.code = code;
        return this;
    }

    private void setContent(int contentId, NoticeParam... args) {
        this.contentId = contentId;
        if(args != null && args.length > 0) {
            paramList = args;
        }
    }

    public GameException content(int contentId, String defaultMessage, NoticeParam... args){
        defaultMessage = StrTool.format(defaultMessage, args);
        if(contentId == 0){
            setContent(0, new NoticeParam(defaultMessage));
        }else{
            setContent(contentId, args);
        }
        this.message = defaultMessage;
        return this;
    }

    public GameException content(int contentId, String defaultMessage, Object... args){
        NoticeParam[] params = null;
        if(ArrayUtils.isNotEmpty(args)){
            params = new NoticeParam[args.length];
            for(int i=0; i<args.length; ++i){
                params[i] = new NoticeParam(args[i]);
            }
        }
        return content(contentId, defaultMessage, params);
    }

    public GameException content(int contentId, Object... args){
        return content(contentId, "", args);
    }

    public GameException content(String text) {
        return content(0, text);
    }

    public GameResult toResult() {
        GameResult r = new GameResult();
        r.code = this.code;
        r.message = this.message;
        r.contentId = this.contentId;
        r.paramList = this.paramList;
        return r;
    }

}
